<template>
  <div class="double-bar-chart">
    <div ref="barChart_left" class="bar-chart"></div>
    <div ref="barChart_right" class="bar-chart"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/title';
import 'echarts/lib/component/grid';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/legend';
import mixin from './mixin';

export default {
  name: 'DoubleBarChart',
  mixins: [mixin],
  data() {
    return {
      leftChart: null,
      rightChart: null,
      leftOption: {},
      rightOption: {},
    };
  },
  computed: {
    leftData() {
      return this.data.slice(0, parseInt(this.data.length / 2)).reverse();
    },
    rightData() {
      return this.data.slice(parseInt(this.data.length / 2)).reverse();
    },
  },
  methods: {
    initChart() {
      this.leftChart = echarts.init(this.$refs.barChart_left);
      this.rightChart = echarts.init(this.$refs.barChart_right);
      this.leftOption = this.getDefaultOption();
      this.rightOption = this.getDefaultOption();
      this.addChartEvent(this.leftChart);
      this.addChartEvent(this.rightChart);
    },
    getDefaultOption() {
      return {
        grid: {
          containLabel: true,
          left: 0,
          right: '22.5%',
          bottom: 0,
          ...this.grid,
        },
        title: {
          show: false,
        },
        legend: {
          show: false,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          textStyle: {
            fontSize: 16 * this.scale,
            fontWeight: 'bold',
          },
          formatter: (params) => {
            let tooltip = `<div>${params[0].name}</div>`;
            params.forEach((item) => {
              tooltip += `<div>
                ${item.marker}
                <span style="color: #666;">${item.seriesName}</span>
                <span style="float: right;margin-left: 20px;color: #666;">${item.value || item.value === 0 ? item.value : '-'}${this.unit}</span>
              </div>`;
            });
            return tooltip;
          },
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          borderWidth: 1,
          borderColor: '#E5E5E5',
          extraCssText: 'box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.08);',
        },
        xAxis: {
          type: 'value',
          show: this.showValueAxis,
          name: this.unit,
          nameTextStyle: {
            fontSize: 16 * this.scale,
            color: this.themeColor === 'default' ? 'rgba(0, 0, 0, 0.45)' : this.themeColor,
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            margin: 20 * this.scale,
            fontSize: 16 * this.scale,
            color: this.themeColor === 'default' ? 'rgba(0, 0, 0, 0.45)' : this.themeColor,
          },
          splitLine: {
            show: this.showSplitLine,
            lineStyle: {
              type: 'dashed',
              color: this.themeColor === 'default' ? 'rgba(0, 0, 0, 0.15)' : this.themeColor,
              opacity: 0.5,
            },
          },
        },
        yAxis: {
          type: 'category',
          boundaryGap: true,
          inverse: this.direction === 'vertical',
          axisTick: {
            show: false,
          },
          axisLine: {
            lineStyle: {
              color: this.themeColor === 'default' ? 'rgba(0, 0, 0, 0.45)' : this.themeColor,
            },
          },
          axisLabel: {
            interval: 0,
            margin: 14 * this.scale,
            fontSize: 16 * this.scale,
            color: this.themeColor === 'default' ? '#171F36' : this.themeColor,
            formatter: (value) => value.split('年').join('年\n'),
            ...this.categoryAxisLabel,
          },
          data: [],
        },
        series: [],
      };
    },
    addChartEvent(chart) {
      chart.on('click', (params) => {
        if (params.componentType === 'series') this.$emit('click', params);
      });
      chart.on('legendselectchanged', (params) => {
        if (this.legendClick(params) !== 'default') {
          chart.setOption({
            legend: { selected: { [params.name]: true } },
          });
        }
      });
    },
    updateChart() {
      this.leftOption.title = {
        show: this.title.length > 0,
        text: this.title,
        left: 0,
        textStyle: {
          color: '#000',
          fontSize: 20 * this.scale,
        },
      };
      if (this.showLegend) {
        let legend = [];
        this.valueKeys.forEach((valueKey) => { legend.push({ name: valueKey.name, icon: 'rect' }); });
        this.rightOption.legend = {
          show: this.showLegend,
          right: 0,
          icon: 'rect',
          data: legend,
          textStyle: {
            color: this.themeColor === 'default' ? '#000' : this.themeColor,
            fontSize: 16 * this.scale,
          },
          ...this.legendOption,
        };
      }
      this.setOption(this.leftChart, this.leftOption, this.leftData);
      this.setOption(this.rightChart, this.rightOption, this.rightData);
    },
    setOption(chart, option, data) {
      let max;
      this.data.forEach((item) => {
        this.valueKeys.forEach((valueKey) => {
          if (!max || max < item[valueKey.key]) max = item[valueKey.key];
        });
      });
      option.xAxis.max = max;
      let axis = [];
      let series = [];
      this.valueKeys.forEach((item, index) => {
        series.push({
          type: 'bar',
          barWidth: 24 * this.scale,
          label: {
            show: this.showLabel,
            position: 'right',
            distance: 0,
            fontSize: 14 * this.scale,
            color: '#000',
            formatter: this.label,
          },
          itemStyle: {
            color: this.colors[index] || this.colors[0],
          },
          barGap: '0%',
          showBackground: this.showBackground,
          data: [],
        });
      });
      data.forEach((item, dataIndex) => {
        axis.push(item[this.categoryAxisKey]);
        this.valueKeys.forEach((valueKey, index) => {
          series[index].name = valueKey.name;
          series[index].data.push({
            name: item[this.categoryAxisKey],
            value: item[valueKey.key],
            ...item,
            unit: this.unit,
            itemStyle: {
              color: this.colors[this.colorful ? dataIndex : index] || this.colors[0],
            },
          });
          series[index] = { ...series[index], ...this.seriesOption[valueKey.name] };
        });
      });
      option.yAxis.data = axis;
      option.series = series;
      chart.clear();
      chart.setOption(option);
    },
  },
  beforeDestroy() {
    if (this.leftChart) {
      this.leftChart.dispose();
      this.leftChart = null;
    }
    if (this.rightChart) {
      this.rightChart.dispose();
      this.rightChart = null;
    }
  },
};
</script>

<style lang="scss" scoped>
.double-bar-chart {
  width: 100%;
  display: flex;
  .bar-chart {
    width: 50%;
    height: 100%;
  }
}
</style>
